package com.elepant.lambda;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

public class LambdaTest {

    /*
        java去实现 group by + group_concat的功能 (相当于行转列)
        最终实现效果：
        [Student{name='李四', age=13, hobby='皮球'}, Student{name='张三', age=12,16, hobby='足球,篮球,水球'}, Student{name='王五', age=12,17, hobby='排球,水球'}]
     */
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        Student a = new Student("张三", "12", "足球");
        Student b = new Student("张三", "16", "篮球");
        Student b1 = new Student("张三", "16", "水球");
        Student c = new Student("王五", "17", "排球");
        Student d = new Student("李四", "13", "皮球");
        Student e = new Student("王五", "12", "水球");
        list.add(a);
        list.add(b);
        list.add(b1);
        list.add(c);
        list.add(d);
        list.add(e);
        List<Student> stList = list.stream()
                .collect(groupingBy(Student::getName))
                .entrySet()
                .stream()
                .map(stEntity -> {
                    // 去重用set即可
                    Set<String> ages = new HashSet<>();

                    //如果不需要去重,用list即可
                    List<String> hobbys = new ArrayList<>();

                    stEntity.getValue().stream()
                            .peek(st -> ages.add(st.getAge()))
                            .forEach(st -> hobbys.add(st.getHobby()));

                    return new Student(stEntity.getKey(),
                            String.join(",", ages),
                            String.join(",", hobbys));
                })
                .collect(Collectors.toList());

        System.out.println(stList);
    }
}

class Student{
    private String name;
    private String age;
    private String hobby;

    public Student(String name, String age, String hobby) {

        this.name = name;
        this.age = age;
        this.hobby = hobby;
    }
    public String getName() {
        return name;
    }
    public String getAge() {
        return age;
    }
    public String getHobby() {
        return hobby;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", hobby='" + hobby + '\'' +
                '}';
    }

}
